//
//  RecordFirstViewController.m
//  BiologyLibrary
//
//  Created by milo on 16/7/2.
//  Copyright © 2016年 youxh. All rights reserved.
//

#import "RecordFirstViewController.h"
#import "RecordviewCell.h"
#import "NXfirststepViewController.h"
#import "NXNinthStepViewController.h"
#import "LBXScanViewStyle.h"
#import "ToChannelViewController.h"
@implementation RecordFirstViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setNaviBarTitle:self.recordName];
    _NewRecordArray=[[NSMutableArray alloc]init];
    // 创建一个自定义的按钮，并添加到导航条左侧。
    UIButton *btnNaviLeft = [CustomNaviBarView createImgNaviBarBtnByImgNormal:@"bar_left_image"
                                                                 imgHighlight:@"bar_left_image_f"
                                                                       target:self
                                                                       action:@selector(btnNaviLeftClick)];
    [self setNaviBarLeftBtn:btnNaviLeft];
    // 创建一个自定义的按钮，并添加到导航条右侧。
    UIButton*_btnNaviRight = [CustomNaviBarView
                              createNormalNaviBarBtnByTitle:@"新建"
                              target:self
                              action:@selector(selecttype)];
    [self setNaviBarRightBtn:_btnNaviRight];
    
    _editButton = [[UIButton alloc]initWithFrame:
                   CGRectMake(10, 69,
                              (fWidth_Current-50)/4, 40)];
    _editButton.backgroundColor=[UIColor colorWithRed:0.22 green:0.57 blue:0.91 alpha:1.0];
    _editButton.layer.cornerRadius=5;
    [_editButton setTitle:@"编辑" forState:UIControlStateNormal];
    _editButton.clipsToBounds=YES;
    [_editButton addTarget:self
                    action:@selector(editClick:)
          forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_editButton];
    
    _cancelButton = [[UIButton alloc]initWithFrame:
                   CGRectMake(10, 69,
                              (fWidth_Current-50)/4, 40)];
    _cancelButton.backgroundColor=[UIColor colorWithRed:0.16 green:0.19 blue:0.24 alpha:1.0];
    _cancelButton.layer.cornerRadius=5;
    [_cancelButton setTitle:@"取消" forState:UIControlStateNormal];
    _cancelButton.clipsToBounds=YES;
    [_cancelButton addTarget:self
                    action:@selector(cancelClick:)
          forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_cancelButton];
    
    _deleteButton = [[UIButton alloc]initWithFrame:
                     CGRectMake(20 + (fWidth_Current-50)/4, 69,
                                (fWidth_Current-50)/4, 40)];
    _deleteButton.backgroundColor=[UIColor redColor];
    _deleteButton.layer.cornerRadius=5;
    [_deleteButton setTitle:@"删除" forState:UIControlStateNormal];
    _deleteButton.clipsToBounds=YES;
    [_deleteButton addTarget:self
                      action:@selector(deleteClick:)
            forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_deleteButton];
    
    _uploadButton = [[UIButton alloc]initWithFrame:
                            CGRectMake(40 + (fWidth_Current - 50)/4 * 3 , 69,
                                       (fWidth_Current - 50)/4, 40)];
    _uploadButton.backgroundColor=[UIColor colorWithRed:0.22 green:0.57 blue:0.91 alpha:1.0];
    _uploadButton.layer.cornerRadius=5;
    [_uploadButton setTitle:@"上传" forState:UIControlStateNormal];
    _uploadButton.clipsToBounds=YES;
    [_uploadButton addTarget:self
                   action:@selector(uploadClick:)
         forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_uploadButton];
    
    _modifyButton = [[UIButton alloc] initWithFrame:CGRectMake(30 + (fWidth_Current - 50)/4 * 2 , 69,
                                                               (fWidth_Current - 50)/4, 40)];
    _modifyButton.backgroundColor=[UIColor colorWithRed:0.22 green:0.57 blue:0.91 alpha:1.0];
    _modifyButton.layer.cornerRadius=5;
    [_modifyButton setTitle:@"修改" forState:UIControlStateNormal];
    _modifyButton.clipsToBounds=YES;
    [_modifyButton addTarget:self
                      action:@selector(modifyClick:)
            forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_modifyButton];
    
    
    _listview=[[UITableView alloc]initWithFrame:CGRectMake(10, 69 + 40, fWidth_Current-20, fHeight_Current- 69 - 40)];
    _listview.backgroundColor = [UIColor clearColor];
    _listview.separatorStyle = UITableViewCellSeparatorStyleNone;
    _listview.dataSource = self;
    _listview.delegate = self;
    _listview.showsVerticalScrollIndicator=NO;
    _listview.allowsMultipleSelectionDuringEditing = YES;
    [self.view addSubview:_listview];
    
    _uploadRecordArray = [[NSMutableArray alloc] init];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [_uploadRecordArray removeAllObjects];
    [_editButton setHidden:NO];
    [_cancelButton setHidden:YES];
    [_deleteButton setHidden:YES];
    [_uploadButton setHidden:YES];
    [_modifyButton setHidden:YES];
    [_listview setEditing:NO animated:YES];
    
    recordarr = [Record findWithFormat:@"WHERE %@ = %d ",@"type", self.recordType];
    [_listview reloadData];
}

-(void)editClick:(UIButton *)sender
{
    [_uploadRecordArray removeAllObjects];
    [_listview setEditing:!_listview.isEditing animated:YES];
    [_editButton setHidden:!_editButton.hidden];
    [_cancelButton setHidden:!_cancelButton.hidden];
    [_deleteButton setHidden:!_deleteButton.hidden];
    [_uploadButton setHidden:!_uploadButton.hidden];
    [_modifyButton setHidden:!_modifyButton.hidden];
}

-(void)cancelClick:(UIButton *)sender
{
    [_uploadRecordArray removeAllObjects];
    [_listview setEditing:!_listview.isEditing animated:YES];
    [_editButton setHidden:!_editButton.hidden];
    [_cancelButton setHidden:!_cancelButton.hidden];
    [_deleteButton setHidden:!_deleteButton.hidden];
    [_uploadButton setHidden:!_uploadButton.hidden];
    [_modifyButton setHidden:!_modifyButton.hidden];

}

-(void)deleteClick:(UIButton *)sender
{
    if([_uploadRecordArray count] < 1)
    {
        [self.view hideToastActivityWithError:@"请选择需要删除的记录！" completion:nil];
        return;
    }
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                    message:@"确定删除选中样本？"
                                                   delegate:self
                                          cancelButtonTitle:@"取消" otherButtonTitles:@"确定",nil];
    alert.tag = 2;
    [alert show];
}

-(void)selecttype
{
    if (self.recordType == 4 || self.recordType == 5) {
        UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@"请选择新建方式" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"从当日血样本中导入",@"扫码",nil];
        [sheet showInView:self.view];
    }else
    {
        [self addnew];
    }
}

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        NSArray *tmprecordarr = [Record findWithFormat:@"WHERE %@ = %d ",@"type", 1];
        NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:0];
        NSMutableArray *mutableName = [NSMutableArray arrayWithCapacity:0];
        for (Record *r in recordarr) {
            [mutableName addObject:r.recordId];
        }
        for (Record *record in tmprecordarr) {
            if ([self checkTheDate:record.creatTime]&&![mutableName containsObject:record.recordId]) {
                record.name = self.recordName;
                [mutableArray addObject:record];
            }
        }
        if (mutableArray.count == 0) {
            [self.view makeToast:@"暂无当日采集的血样本或血样本都已导入" position:@"center"];
            return;
        }
        ToChannelViewController *vc = [[ToChannelViewController alloc] init];
        vc.NewRecordArray = mutableArray;
        NSMutableArray *mtarray = [NSMutableArray arrayWithArray:recordarr];
        vc.selectBlock = ^(NSMutableArray * _Nonnull array) {
            for (Record *record in array) {
                record.type = self.recordType;
                record.recordStatus = STATUS_RECORD_NEW;
                if (self.recordType == 4) {
                    record.allStepCount = 7;
                }else
                {
                    record.allStepCount = 8;
                }
                record.creatTime = [[NSDate date] timeIntervalSince1970];
                dispatch_async(dispatch_get_global_queue(0, 0), ^{
                    [record save];
                });
                [mtarray addObject:record];
            }
            recordarr = array;
        };
        [self presentViewController:vc animated:YES completion:NULL];
        
    }else if(buttonIndex == 1)
    {
        [self addnew];
    }
}

- (BOOL)checkTheDate:(double )string{
    
   
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:string];
    BOOL isToday = [[NSCalendar currentCalendar] isDateInToday:date];
    
    
    return isToday;
}

-(void)modifyClick:(UIButton *)sender
{
    if([_uploadRecordArray count] < 1)
    {
        [self.view hideToastActivityWithError:@"请选择需要上传的记录！" completion:nil];
        return;
    }
    NSInteger savedStepCount = -1;
    for (Record *tempRecord in _uploadRecordArray)
    {
        if(savedStepCount!=-1&&tempRecord.savedStepCount != savedStepCount)
        {
            [self.view hideToastActivityWithError:@"请选择相同步数的记录！" completion:nil];
            return;
        }
        savedStepCount = tempRecord.savedStepCount;
    }
    if ([_uploadRecordArray count] > 1) {
        NXfirststepViewController *NXfirststepVC = [[NXfirststepViewController alloc] init];
        NXfirststepVC.NewRecordArray=_uploadRecordArray;
        [self.navigationController pushViewController:NXfirststepVC animated:YES];
    }
}

-(void)uploadClick:(UIButton *)sender
{
    if([_uploadRecordArray count] < 1)
    {
        [self.view hideToastActivityWithError:@"请选择需要上传的记录！" completion:nil];
        return;
    }
    
    for (Record *tempRecord in _uploadRecordArray)
    {
        if(tempRecord.recordStatus != STATUS_RECORD_FINISHED)
        {
            [self.view hideToastActivityWithError:@"未完成的记录不可上传！" completion:nil];
            return;
        }
    }
    
    
        if (_uploadRecordArray.count != 0) {
            [self updateRecord:_uploadRecordArray.firstObject];
        }

//    [self editClick: _editButton];
}

-(void) updateRecord:(Record *)record
{
    NSDictionary*dic=[NSDictionary dictionaryWithObjectsAndKeys:record.getDetailDict,@"record", nil];
    [self.view makeToastActivityWithMessage:@"上传服务器"];
    self.view.userInteractionEnabled=NO;
    NSDictionary *parametersDict = [NSDictionary dictionaryWithObjectsAndKeys:
                                    [NSString stringWithFormat:@"%ld",(long)record.type],@"sampleType",
                                    [dic JSONString],@"record",
                                    record.recordId,@"sampleNO",nil];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    //    // 设置超时时间
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    manager.requestSerializer.timeoutInterval = 15.f;
    [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    [manager.requestSerializer setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [manager POST:[NSString stringWithFormat:@"%@saveSampleForApp.do",APPDelegate.baseUrl]
       parameters:parametersDict
          success:^(AFHTTPRequestOperation *operation, id responseObject) {
              if([responseObject isKindOfClass:[NSDictionary class]] && [[responseObject allKeys] containsObject:@"error"]){

                  [self.view hideToastActivityWithError:[responseObject objectForKey:@"error"] completion:nil];
              }else{
                  [self saveOnlineData:record];
                  [self.view hideToastActivityWithSuccess:@"上传成功" completion:nil];
                  [self removeObjectAndReleaseAddress:record];
                  [_uploadRecordArray removeObject:record];
                  recordarr = [Record findWithFormat:@"WHERE %@ = %d ",@"type", self.recordType];
                  [_listview reloadData];
                  NSString*sampleid=[NSString stringWithFormat:@"%@",[[responseObject objectForKey:@"sample"]objectForKey:@"id"]];
                  NSString*sampletype=[NSString stringWithFormat:@"%@",[[responseObject objectForKey:@"sample"]objectForKey:@"type"]];
                  [self uploadPictures:sampleid sampletype:sampletype record:record];
              }
          } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
              self.view.userInteractionEnabled=YES;
              DLog(@"operation %@",operation.responseString);
              if ([error code] == 1) {
                  
                  [self.view hideToastActivityWithError:d_Error_NetWork completion:nil];
              }else if([error code] == 2){
                  
                  [self.view hideToastActivityWithError:d_Error_TimeOut completion:nil];
              }else{
                  
                  [self.view hideToastActivityWithError:d_Error_UnKnow completion:nil];
              }
          }];
}

#pragma mark - UITableViewDataSource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 1;
    
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return [recordarr count];//返回标题数组中元素的个数来确定分区的个数
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 40;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section==0) {
        return 10;
    }else{
        return 0.1;

    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 10;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView*headview=[[UIView alloc]initWithFrame:CGRectMake(0, 0, fWidth_Current, 18)];
    headview.backgroundColor=[UIColor clearColor];
    return headview;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView*headview=[[UIView alloc]initWithFrame:CGRectMake(0, 0, fWidth_Current, 18)];
    headview.backgroundColor=[UIColor clearColor];
    return headview;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"CustomCell";
    RecordviewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"RecordviewCell" owner:self options:nil];
    
    for (id oneObject in nib)
    {
        if ([oneObject isKindOfClass:[RecordviewCell class]])
        {
            cell = (RecordviewCell *)oneObject;
        }
    }
    cell.backgroundColor=[UIColor colorWithRed:0.16 green:0.19 blue:0.24 alpha:1.0];
    cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
    
    Record *tempRecord = (Record *)[recordarr objectAtIndex:indexPath.section];

    cell.titlelab.text = tempRecord.recordId;
    cell.steplab.text = [NSString stringWithFormat:@"第%ld步",tempRecord.savedStepCount];
    return cell;

}
#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    Record *tempRecord = (Record *)[recordarr objectAtIndex:indexPath.section];
    if (!tableView.editing)
    {
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        _selectedRecord = tempRecord;
        [self gotoSelectedRecord:tempRecord];
    }else
    {
        [tempRecord setDetailDict:[NSMutableDictionary dictionaryWithDictionary:
                                   [tempRecord.recordDetail objectFromJSONString]]];
        [_uploadRecordArray addObject:tempRecord];
        [_uploadButton setHidden:!([_uploadRecordArray count] > 0)];
    }
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
    Record *tempRecord = (Record *)[recordarr objectAtIndex:indexPath.section];
    if (_uploadRecordArray.count > 0 && [_uploadRecordArray containsObject:tempRecord])
    {
        [_uploadRecordArray removeObject:tempRecord];
    }}

//- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    if(tableView.isEditing)
//    {
//        Record *tempRecord = (Record *)[recordarr objectAtIndex:indexPath.section];
//        if (tempRecord.recordStatus != STATUS_RECORD_FINISHED)
//        {
//            return NO;
//        }
//    }
//
//    return YES;
//}
//
//- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    if (editingStyle == UITableViewCellEditingStyleDelete) {
//        Record *tempRecord = (Record *)[recordarr objectAtIndex:indexPath.section];
//        _selectedRecord = tempRecord;
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@" 确定删除该样本？" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确定",nil];
//        alert.delegate=self;
//        alert.tag=2;
//        [alert show];
//    }
//}

- (void) gotoSelectedRecord :(Record *) tempRecord {
    
    [tempRecord setDetailDict:[NSMutableDictionary dictionaryWithDictionary:
                               [tempRecord.recordDetail objectFromJSONString]]];
    if(tempRecord.type == TYPE_RECORD_XUEYANGBEN){
        if(tempRecord.recordStatus==STATUS_RECORD_NEW) {
            tempRecord.savedStepCount=0;
            NXfirststepViewController*NXfirststepVC = [[NXfirststepViewController alloc] init];
//            NXfirststepVC.record = tempRecord;
            NSMutableArray <Record *>*nowArr=[[NSMutableArray alloc]init];
            [nowArr addObject:tempRecord];
            NXfirststepVC.NewRecordArray=nowArr;
            [self.navigationController pushViewController:NXfirststepVC animated:YES];
        }else if (tempRecord.recordStatus==STATUS_RECORD_FINISHED){
            nowfinishrecord=tempRecord.getDetailDict;
            nowrecorestr=tempRecord.recordId;
            nowtype=@"1";
//            [self uploadPictures];

            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"该样本记录已经完成，是否上传？" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确定",nil];
            alert.delegate=self;
            alert.tag=1;
            [alert show];
        }
        
    }else if (tempRecord.type == TYPE_RECORD_SHITIZHONGNIU){
        if (tempRecord.recordStatus==STATUS_RECORD_SAVED) {
            tempRecord.savedStepCount=7;
            
            NXNinthStepViewController*NXNinthStepVC = [[NXNinthStepViewController alloc] init];
            NSMutableArray <Record *>*nowArr=[[NSMutableArray alloc]init];
            [nowArr addObject:tempRecord];
            NXNinthStepVC.NewRecordArray = nowArr;
            [self.navigationController pushViewController:NXNinthStepVC animated:YES];
        }else if(tempRecord.recordStatus==STATUS_RECORD_NEW) {
            tempRecord.savedStepCount=0;
            NSMutableArray <Record *>*nowArr=[[NSMutableArray alloc]init];
            [nowArr addObject:tempRecord];
            NXfirststepViewController*NXfirststepVC = [[NXfirststepViewController alloc] init];
            NXfirststepVC.NewRecordArray = nowArr;
            [self.navigationController pushViewController:NXfirststepVC animated:YES];
        }else if (tempRecord.recordStatus==STATUS_RECORD_FINISHED){
            nowfinishrecord=tempRecord.getDetailDict;
            nowrecorestr=tempRecord.recordId;
            nowtype=@"2";
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"该样本记录已经完成，是否上传？" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确定",nil];
            alert.delegate=self;
            alert.tag=1;
            [alert show];
        }
        
    }else if (tempRecord.type == TYPE_RECORD_NANGXINGZHONGNIU){
        if (tempRecord.recordStatus==STATUS_RECORD_SAVED) {
            tempRecord.savedStepCount=8;
            NSMutableArray <Record *>*nowArr=[[NSMutableArray alloc]init];
            [nowArr addObject:tempRecord];
            NXNinthStepViewController*NXNinthStepVC = [[NXNinthStepViewController alloc] init];
            NXNinthStepVC.NewRecordArray = nowArr;
            [self.navigationController pushViewController:NXNinthStepVC animated:YES];
        }else if(tempRecord.recordStatus==STATUS_RECORD_NEW) {
            tempRecord.savedStepCount=0;
            NSMutableArray <Record *>*nowArr=[[NSMutableArray alloc]init];
            [nowArr addObject:tempRecord];
            NXfirststepViewController*NXfirststepVC = [[NXfirststepViewController alloc] init];
            NXfirststepVC.NewRecordArray = nowArr;
            [self.navigationController pushViewController:NXfirststepVC animated:YES];
        }else if (tempRecord.recordStatus==STATUS_RECORD_FINISHED){
            nowfinishrecord=tempRecord.getDetailDict;
            nowrecorestr=tempRecord.recordId;
            nowtype=@"3";
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"该样本记录已经完成，是否上传？" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确定",nil];
            alert.delegate=self;
            alert.tag=1;
            [alert show];
        }
        
    }else if (tempRecord.type == TYPE_RECORD_XUEJIANGYANGBEN){
        if (tempRecord.recordStatus==STATUS_RECORD_SAVED) {
            
        }else if(tempRecord.recordStatus==STATUS_RECORD_NEW) {
            tempRecord.savedStepCount=0;
            NSMutableArray <Record *>*nowArr=[[NSMutableArray alloc]init];
            [nowArr addObject:tempRecord];
            NXfirststepViewController*NXfirststepVC = [[NXfirststepViewController alloc] init];
            NXfirststepVC.NewRecordArray = nowArr;
            [self.navigationController pushViewController:NXfirststepVC animated:YES];
        }else if (tempRecord.recordStatus==STATUS_RECORD_FINISHED){
            nowfinishrecord=tempRecord.getDetailDict;
            nowrecorestr=tempRecord.recordId;
            nowtype=@"4";

            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"该样本记录已经完成，是否上传？" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确定",nil];
            alert.delegate=self;
            alert.tag=1;
            [alert show];
        }
    }else if (tempRecord.type == TYPE_RECORD_XUEQINGYANGBEN){
        if (tempRecord.recordStatus==STATUS_RECORD_SAVED) {
            
        }else if(tempRecord.recordStatus==STATUS_RECORD_NEW) {
            tempRecord.savedStepCount=0;
            NSMutableArray <Record *>*nowArr=[[NSMutableArray alloc]init];
            [nowArr addObject:tempRecord];
            NXfirststepViewController*NXfirststepVC = [[NXfirststepViewController alloc] init];
            NXfirststepVC.NewRecordArray = nowArr;
            [self.navigationController pushViewController:NXfirststepVC animated:YES];
        }else if (tempRecord.recordStatus==STATUS_RECORD_FINISHED){
            nowfinishrecord=tempRecord.getDetailDict;
            nowrecorestr=tempRecord.recordId;
            nowtype=@"5";

            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"该样本记录已经完成，是否上传？" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确定",nil];
            alert.delegate=self;
            alert.tag=1;
            [alert show];
        }
    }
}

#pragma mark UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (alertView.tag==1) {
        if (buttonIndex==1) {
            NSLog(@"%@",nowfinishrecord);
            NSDictionary*dic=[NSDictionary dictionaryWithObjectsAndKeys:nowfinishrecord,@"record", nil];
            NSLog(@"dic======%@",dic);
            [self.view makeToastActivityWithMessage:@"上传服务器"];
            self.view.userInteractionEnabled=NO;
            NSDictionary *parametersDict = [NSDictionary dictionaryWithObjectsAndKeys:
                                            nowtype,@"sampleType",
                                            [dic JSONString],@"record",
                                            nowrecorestr,@"sampleNO",nil];
            AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
            //    // 设置超时时间
            [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
            manager.requestSerializer.timeoutInterval = 15.f;
            [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
            [manager.requestSerializer setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
            [manager POST:[NSString stringWithFormat:@"%@saveSampleForApp.do",APPDelegate.baseUrl]
               parameters:parametersDict
                  success:^(AFHTTPRequestOperation *operation, id responseObject) {
                      
                      DLog(@"responseObject %@",responseObject);
                      if([responseObject isKindOfClass:[NSDictionary class]] && [[responseObject allKeys] containsObject:@"error"]){
                          [self.view hideToastActivityWithError:[responseObject objectForKey:@"error"] completion:nil];
                      }else{
                          [self saveOnlineData:_selectedRecord];
                          [self.view hideToastActivityWithSuccess:@"上传成功" completion:nil];
                          [self removeObjectAndReleaseAddress:_selectedRecord];
                          recordarr = [Record findWithFormat:@"WHERE %@ = %d ",@"type", self.recordType];
                          [_listview reloadData];
                          NSString*sampleid=[NSString stringWithFormat:@"%@",[[responseObject objectForKey:@"sample"]objectForKey:@"id"]];
                          NSString*sampletype=[NSString stringWithFormat:@"%@",[[responseObject objectForKey:@"sample"]objectForKey:@"type"]];
                          [self uploadPictures:sampleid sampletype:sampletype record:_selectedRecord];
                      }
                  } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                      self.view.userInteractionEnabled=YES;
                      
                      DLog(@"operation %@",operation.responseString);
                      if ([error code] == 1) {
                          
                          [self.view hideToastActivityWithError:d_Error_NetWork completion:nil];
                      }else if([error code] == 2){
                          
                          [self.view hideToastActivityWithError:d_Error_TimeOut completion:nil];
                      }else{
                          
                          [self.view hideToastActivityWithError:d_Error_UnKnow completion:nil];
                      }
                  }];

            
        }
    }
    else if (alertView.tag==2)
    {
        if (buttonIndex==1)
        {
            for (Record *tempRecord in _uploadRecordArray)
            {
                NSLog(@"准备删除编号为：%@的记录",tempRecord.recordId);
                [self removeObjectAndReleaseAddress:tempRecord];
            }
            
            [self editClick: _editButton];
            
            recordarr = [Record findWithFormat:@"WHERE %@ = %d ",@"type", self.recordType];
            [_listview reloadData];
        }
    }
}

-(void) removeObjectAndReleaseAddress:(Record *) tempRecord
{
    [tempRecord deleteObject];
    [self removeAddressObject];
}

//上传成功保存为线上数据
-(void)saveOnlineData:(Record *)model
{
    NSMutableArray *onlineArray = [[[NSUserDefaults standardUserDefaults] objectForKey:@"onlineData"] mutableCopy];
    [onlineArray addObject:@[@"online",[NSNumber numberWithInteger:model.type],model.recordId]];
    [[NSUserDefaults standardUserDefaults] setObject:onlineArray forKey:@"onlineData"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

-(void)removeAddressObject{
    if ([nowtype isEqualToString:@"1"]) {
        return;
    }
    if ([nowtype isEqualToString:@"2"]) {
        NSMutableArray*temparr=[nowfinishrecord objectForKey:@"step9"];
        for (int i=1; i<temparr.count; i++) {
            NSDictionary*dic=[temparr objectAtIndex:i];
            NSString*addressstr=[dic objectForKey:@"answer"];
            if (![addressstr isEqualToString:@"请选择"]) {
                [APPDataCenter removeusedaddressArray:addressstr];
            }
        }
        
    }if ([nowtype isEqualToString:@"3"]) {
        NSMutableArray*temparr=[nowfinishrecord objectForKey:@"step9"];
        for (int i=1; i<temparr.count; i++) {
            NSDictionary*dic=[temparr objectAtIndex:i];
            NSString*addressstr=[dic objectForKey:@"answer"];
            if (![addressstr isEqualToString:@"请选择"]) {
                [APPDataCenter removeusedaddressArray:addressstr];
            }
        }
        NSMutableArray*temparr1=[nowfinishrecord objectForKey:@"step13"];
        for (int i=1; i<temparr1.count; i++) {
            NSDictionary*dic=[temparr1 objectAtIndex:i];
            NSString*addressstr=[dic objectForKey:@"answer"];
            if (![addressstr isEqualToString:@"请选择"]) {
                [APPDataCenter removeusedaddressArray:addressstr];
            }
        }

        
    }if ([nowtype isEqualToString:@"4"]) {
        NSMutableArray*temparr=[nowfinishrecord objectForKey:@"step5"];
        for (int i=1; i<temparr.count; i++) {
            NSDictionary*dic=[temparr objectAtIndex:i];
            NSString*addressstr=[dic objectForKey:@"answer"];
            if (![addressstr isEqualToString:@"请选择"]) {
                [APPDataCenter removeusedaddressArray:addressstr];
            }
        }
        
    }if ([nowtype isEqualToString:@"5"]) {
        NSMutableArray*temparr=[nowfinishrecord objectForKey:@"step6"];
        for (int i=1; i<temparr.count; i++) {
            NSDictionary*dic=[temparr objectAtIndex:i];
            NSString*addressstr=[dic objectForKey:@"answer"];
            if (![addressstr isEqualToString:@"请选择"]) {
                [APPDataCenter removeusedaddressArray:addressstr];
            }
        }
        
    }

    
    
}
-(void)uploadPictures:(NSString *)sempleid sampletype:(NSString *)type record:(Record *)model{
    NSArray*_imageArray=[[NSArray alloc]init];
    if ([type isEqualToString:@"1"]) {
        _imageArray=[[[model.getDetailDict objectForKey:@"step2"] objectAtIndex:0] objectForKey:@"answer"];
    }else if([type isEqualToString:@"2"]||[type isEqualToString:@"3"]){
        _imageArray=[[[model.getDetailDict objectForKey:@"step5"] objectAtIndex:0] objectForKey:@"answer"];
    }
    [self.view makeToastActivityWithMessage:@"上传图片..."];

    NSDictionary *parametersDict = [NSDictionary dictionaryWithObjectsAndKeys:
                                    type,@"sampleType",
                                    sempleid,@"sampleId",
                                    nil];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    //如果还需要上传其他的参数，参考上面的POST请求，创建一个可变字典，存入需要提交的参数内容，作为parameters的参数提交
    [manager POST:[NSString stringWithFormat:@"%@upload.do",APPDelegate.baseUrl]
       parameters:parametersDict constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
     {
         //_imageArray就是图片数组，我的_imageArray里面存的都是图片的data，下面可以直接取出来使用，如果存的是image，将image转换data的方法如下：NSData *imageData = UIImageJPEGRepresentation(image, 0.7);
         if (_imageArray.count > 0 ){
             for(int i = 0;i < _imageArray.count;i ++){

                 //上传的参数名
                 NSString* filepath = [NSString stringWithFormat:@"%@",[_imageArray objectAtIndex:i]];
                 NSString *fileName = [NSString stringWithFormat:@"%@",[filepath substringFromIndex:[filepath length] - 10]];
                 NSLog(@"fileName = %@",fileName);
                 UIImage*savedimage=[[UIImage alloc]initWithContentsOfFile:filepath];
                 NSData*data=UIImageJPEGRepresentation(savedimage, 0.1);
                 if (data == nil) {
                     continue;
                 }
                 [formData appendPartWithFileData:data
                                             name:[NSString stringWithFormat:@"uploadPaths%@",@(i)]
                                         fileName:fileName
                                         mimeType:@"image/jpeg"];
             }
         }
        
         
     }success:^(NSURLSessionDataTask *task, id responseObject) {
         
         //关闭系统风火轮
         [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
         
         //json解析
         [self.view hideToastActivityWithSuccess:@"上传图片成功" completion:nil];
//         NSInteger index = [_uploadRecordArray indexOfObject:model];
         if(_uploadRecordArray.count>0){
             [self updateRecord:_uploadRecordArray.firstObject];

         }
       

         DLog(@"responseObject %@",responseObject);
     } failure:^(NSURLSessionDataTask *task, NSError *error) {
         [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;

     }];

}
-(void)btnNaviLeftClick
{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)addnew{
    
    CodeBarViewController *codeBarVC = [[CodeBarViewController alloc] init];
    codeBarVC.delegate = self;
    //设置扫码区域参数设置
    //创建参数对象
    LBXScanViewStyle *style = [[LBXScanViewStyle alloc]init];
    //矩形区域中心上移，默认中心点为屏幕中心点
    style.centerUpOffset = fHeight_StatueBar+fHeight_Nav;
    //扫码框周围4个角的类型,设置为外挂式
    style.photoframeAngleStyle = LBXScanViewPhotoframeAngleStyle_Outer;
    //扫码框周围4个角绘制的线条宽度
    style.photoframeLineW = 6;
    //扫码框周围4个角的宽度
    style.photoframeAngleW = 24;
    //扫码框周围4个角的高度
    style.photoframeAngleH = 24;
    //扫码框内 动画类型 --线条上下移动
    style.anmiationStyle = LBXScanViewAnimationStyle_LineMove;
    //线条上下移动图片
    style.animationImage = [UIImage imageNamed:@"CodeScan.bundle/qrcode_scan_light_green"];
    codeBarVC.style = style;
    codeBarVC.isQQSimulator = YES;
    codeBarVC.isVideoZoom = YES;
    codeBarVC.type = self.recordType;
    [self presentViewController:codeBarVC animated:YES completion:nil];
}

#pragma mark - CodeBarViewControllerDelegate
-(void)didSaoMiaoFinished:(CodeBarViewController *)codeBarViewController
                 withCodeArr:(NSArray *)codeArr{
    
    [_NewRecordArray removeAllObjects];
    for (NSString *codeStr in codeArr) {
        Record *record = [[Record alloc] init];
        record.recordId = codeStr;
        record.type = self.recordType;
        record.name = self.recordName;
        record.recordStatus = STATUS_RECORD_NEW;
        record.allStepCount = self.allStepCount;
        record.creatTime = [[NSDate date] timeIntervalSince1970];
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            [record save];
        });
        [_NewRecordArray addObject:record];
    }
    
    if (self.recordType == 1) {
        NXfirststepViewController *NXfirststepVC = [[NXfirststepViewController alloc] init];
        NXfirststepVC.NewRecordArray=_NewRecordArray;
        [self.navigationController pushViewController:NXfirststepVC animated:YES];
    }else{
        NXfirststepViewController*NXfirststepVC = [[NXfirststepViewController alloc] init];
        NXfirststepVC.NewRecordArray=_NewRecordArray;
        [self.navigationController pushViewController:NXfirststepVC animated:YES];
    }

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
